package com.ft.turorial.spring.boot.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ft.turorial.spring.boot.domain.User;
import com.ft.turorial.spring.boot.service.UserRunAsService;
import com.ft.turorial.spring.boot.service.UserService;
import com.ft.turorial.spring.boot.web.util.SessionUtil;

@Controller
@RequestMapping("/runas")
public class RunAsController {
	
	@Resource
	private UserRunAsService userRunAsService;
	@Resource
	private UserService userService;
	
	@RequestMapping
    public String runasList(Model model) {
		User curUser = SessionUtil.getUser();
		List<User> toUsers = userRunAsService.findByFromUserIds(curUser.getId());
		List<User> fromUsers = userRunAsService.findByToUserIds(curUser.getId());
        model.addAttribute("fromUsers", fromUsers);
        model.addAttribute("toUsers", toUsers);

        List<User> allUsers = userService.findAll();
        allUsers.remove(curUser);
        model.addAttribute("allUsers", allUsers);

        for (User user : allUsers) {
			System.out.println("User:"+user.getId()+" " + toUsers.contains(user) + toUsers.toString());
		}
        
        Subject subject = SecurityUtils.getSubject();
        model.addAttribute("isRunas", subject.isRunAs());
        //表示当前用户是否是RunAs用户，即已经切换身份了
        if(subject.isRunAs()) {
        	//得到切换身份之前的身份，一个用户可以切换很多次身份，之前的身份使用栈数据结构来存储；
            String previousUsername = (String)subject.getPreviousPrincipals().getPrimaryPrincipal();
            model.addAttribute("previousUsername", previousUsername);
        }
        model.addAttribute("curUser", curUser);
        return "security/runas/list";
    }

    /**
     * 授予身份
	 *    把当前用户身份授予给另一个用户，这样另一个用户可以切换身份到该用户
     * @param toUserId
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/grant/{toUserId}")
    public String grant(@PathVariable("toUserId") Integer toUserId,RedirectAttributes redirectAttributes) {
    	User curUser = SessionUtil.getUser();
        if(curUser.getId().equals(toUserId)) {
            redirectAttributes.addFlashAttribute("msg", "自己不能切换到自己的身份");
            return "redirect:/runas";
        }
        userRunAsService.grantRunAs(curUser.getId(), toUserId);
        redirectAttributes.addFlashAttribute("msg", "操作成功");
        return "redirect:/runas";
    }

    /**
     * 回收身份
     *    把授予给某个用户的身份回收回来。
     * @param loginUser
     * @param toUserId
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/revoke/{toUserId}")
    public String revoke(@PathVariable("toUserId") Integer toUserId,RedirectAttributes redirectAttributes) {
    	User curUser = SessionUtil.getUser();
        userRunAsService.revokeRunAs(curUser.getId(), toUserId);
        redirectAttributes.addFlashAttribute("msg", "操作成功");
        return "redirect:/runas";
    }

    /**
     * 切换身份
     * @param loginUser
     * @param switchToUserId
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/switchTo/{switchToUserId}")
    public String switchTo(@PathVariable("switchToUserId") Integer switchToUserId,RedirectAttributes redirectAttributes) {
    	User curUser = SessionUtil.getUser();
        Subject subject = SecurityUtils.getSubject();

        User switchToUser = userService.findOne(switchToUserId);
        if(curUser.equals(switchToUser)) {
            redirectAttributes.addFlashAttribute("msg", "自己不能切换到自己的身份");
            return "redirect:/runas";
        }

        if(switchToUser == null || !userRunAsService.exists(curUser.getId(), switchToUserId)) {
            redirectAttributes.addFlashAttribute("msg", "对方没有授予您身份，不能切换");
            return "redirect:/runas";
        }

        subject.runAs(new SimplePrincipalCollection(switchToUser.getUserName(), ""));
        redirectAttributes.addFlashAttribute("msg", "操作成功");
        redirectAttributes.addFlashAttribute("needRefresh", "true");
        return "redirect:/runas";
    }

    /**
     * 切换到上一个身份 
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/switchBack")
    public String switchBack(RedirectAttributes redirectAttributes) {
        Subject subject = SecurityUtils.getSubject();

        if(subject.isRunAs()) {
           subject.releaseRunAs();
        }
        redirectAttributes.addFlashAttribute("msg", "操作成功");
        redirectAttributes.addFlashAttribute("needRefresh", "true");
        return "redirect:/runas";
    }
}
